package game.utils;

import game.bean.PlayerInfo;
import game.frame.MainFrame;
import game.sev.PlayerInfoSev;

import javax.swing.*;
import java.io.*;

/**
 * @author liuyulai
 * 文件工具类
 */
public class FileUtils {
    public static void init() {
        readPlayerList();
        writePlayerInfo();
    }

    public static void readPlayerList() {
        Reader r = null;
        BufferedReader bf = null;
        try {
            r = new FileReader("info/list.txt");
            bf = new BufferedReader(r);
            String str;
            while ((str = bf.readLine()) != null) {
                System.out.println(str);
                String strs[] = str.split("\\s+");
                PlayerInfoSev.list.add(new PlayerInfo(strs[0], Integer.parseInt(strs[1])));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bf.close();
                r.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void writePlayerInfo() {
        Writer writer = null;
        BufferedWriter bw = null;
        try {
            writer = new FileWriter("info/list.txt");
            bw = new BufferedWriter(writer);
            int count = 0;
            PlayerInfoSev.addNewPlayInfo(new PlayerInfo(JOptionPane.showInputDialog("打得不错,请输入你的名字"), MainFrame.playerExp));
            for (PlayerInfo p : PlayerInfoSev.list) {
                count++;
                bw.write(p.getName() + "  " + p.getNum() + "\n");
                bw.flush();
                //满足前5个即可返回
                if (count == 5) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bw.close();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
